﻿using lottery.entity;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;

namespace lottery.admin.Models
{
    public static class SelectListExtension
    {
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                         select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }

        public static SelectList ToSelectList<TEnum>(this TEnum enumObj, object attachEnum)
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                         select new { Id = e, Name = (e as Enum).GetAttachedData<string>(attachEnum) };
            return new SelectList(values, "Id", "Name", enumObj);
        }


        public static IEnumerable<SelectListItem> ToSelectListItems<TEnum>(this TEnum enumObj)
        {
            return from TEnum e in Enum.GetValues(typeof(TEnum))
                   select new SelectListItem()
                   {
                       Selected = (Convert.ToInt32(e) == Convert.ToInt32(enumObj)), //使用DropDownListFor时不需要指定Selected
                       Text = e.ToString(),
                       Value = Convert.ToInt32(e).ToString()
                   };
        }

        public static IEnumerable<SelectListItem> ToSelectListItems<TEnum>(this TEnum enumObj, object attachEnum)
        {
            return from TEnum e in Enum.GetValues(typeof(TEnum))
                   select new SelectListItem()
                   {
                       Selected = (Convert.ToInt32(e) == Convert.ToInt32(enumObj)),
                       Text = (e as Enum).GetAttachedData<string>(attachEnum),
                       Value = Convert.ToInt32(e).ToString()
                   };
        }



        public static IList<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> items,
            Func<T, string> getText, Func<T, string> getValue, string selectValue)
        {
            return items.OrderBy(i => getText(i)).Select(i => new SelectListItem
            {
                Selected = (getValue(i) == selectValue),
                Text = getText(i),
                Value = getValue(i)
            }).ToList();
        }

    }
}
